
//
//  myResumeCellVocie.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/5/12.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import AVFoundation

class LDFinderDetailVoiceCell: LDBaseRecFinderCell {
    
    var myLightLab:UILabel?
    var myAdvLab:UILabel?
    var myExpLab:UILabel?
    var myEduLab:UILabel?
    
    var myLightBtn:baseVoiceButton?
    var myAdvBtn:baseVoiceButton?
    var myExpBtn:baseVoiceButton?
    var myEduBtn:baseVoiceButton?
    
    var lab1:UILabel?
    var lab2:UILabel?
    var lab3:UILabel?
    var lab4:UILabel?
    
    var line_v:UIView?
    var dotimg1:UIImageView?
    var dotimg2:UIImageView?
    var dotimg3:UIImageView?
    var dotimg4:UIImageView?
    
    var resumeDict = NSDictionary() {
        
        didSet{
            
            setupContentData()
//            updataContent()
        }
    }
    
    var aduioPaly:AVAudioPlayer?
    var preVoiceBtn:baseVoiceButton?
    
    var voiceBtnTag = 6666
    var voiceArrApi = [Int:String]()
    //
    dynamic var voiceBtnCurrentTime = NSTimeInterval()
    var currnetTimer:NSTimer?
    //
    //语音name
    var voiceNameArr = [String]()
    //语音isSet
    var voiceIsSetArr = [String]()
    //持续时间
    var vocieDurationArr = [String]()
    //上传时间
    var voiceUploadTime = [String]()
    //
    var voiceBtnArr = [baseVoiceButton]()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setDefaultContent()
    }
    
    func setVoiceBtnTime() {
        
        if self.aduioPaly?.currentTime == nil {
            return
        }
        
        let currenttime = Int((self.aduioPaly?.currentTime)!+1.3)
        
        preVoiceBtn?.timeLab?.text = String(currenttime) + "”"
    }
    
    deinit {
        
        self.aduioPaly?.stop()
    }
    
    func setupContentData() {
        
        //api 单个返回 ,只能单个解析
        let infoDict = resumeDict
        let audioModel = LDMyAudioResumeModel.yy_modelWithDictionary(infoDict as [NSObject : AnyObject])
        
        let audioSet1 = audioModel?.audiohighlights_isset ?? "0"
        let audioSet3 = audioModel?.audiomystrengths_isset ?? "0"
        let audioSet2 = audioModel?.audioworkexperience_isset ?? "0"
        let audioSet4 = audioModel?.audioeduexperience_isset ?? "0"
        voiceIsSetArr = [audioSet1,audioSet2,audioSet3,audioSet4]
        
        let audioDura1 = audioModel?.audiohighlights_duration ?? LDNull
        let audioDura2 = audioModel?.audiomystrengths_duration ?? LDNull
        let audioDura3 = audioModel?.audioworkexperience_duration ?? LDNull
        let audioDura4 = audioModel?.audioeduexperience_duration ?? LDNull
        vocieDurationArr = [audioDura1,audioDura2,audioDura3,audioDura4]
        
        
        let audioUpTime1 = audioModel?.audiohighlights_updated ?? LDNull
        let audioUpTime2 = audioModel?.audiomystrengths_updated ?? LDNull
        let audioUpTime3 = audioModel?.audioworkexperience_updated ?? LDNull
        let audioUpTime4 = audioModel?.audioeduexperience_updated ?? LDNull
        voiceUploadTime = [audioUpTime1,audioUpTime2,audioUpTime3,audioUpTime4]
        
        
        let audioName1 = infoDict["audiohighlights"] as? String ?? LDNull
        let audioName2 = infoDict["audiomystrengths"] as? String ?? LDNull
        let audioName3 = infoDict["audioworkexperience"] as? String ?? LDNull
        let audioName4 = infoDict["audioeduexperience"] as? String ?? LDNull
        voiceNameArr = [audioName1,audioName2,audioName3,audioName4]
        
        
        voiceArrApi[0] = audioName1
        voiceArrApi[1] = audioName2
        voiceArrApi[2] = audioName3
        voiceArrApi[3] = audioName4
        
        let voiceBtnArr = [myLightBtn,myAdvBtn,myExpBtn,myEduBtn]
        let norLabArr = [lab1,lab2,lab3,lab4]
        
        for i in 0..<norLabArr.count {
            
            if voiceIsSetArr[i] == "1" {
                
                voiceBtnArr[i]!.hidden = false
                voiceBtnArr[i]?.timeLab?.text = vocieDurationArr[i] + "“"
                norLabArr[i]!.hidden = true
                
            } else {
                
                voiceBtnArr[i]!.hidden = true
                norLabArr[i]!.hidden = false
            }
        }
    }
    //
    func refreshDruation() {
        
        for i in 0..<vocieDurationArr.count {
            
            voiceBtnArr[i].timeLab!.text = vocieDurationArr[i] + "”"
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func tapVoiceBtn(Btn:baseVoiceButton) {
        Btn.selected = !Btn.selected
        
        preVoiceBtn?.animaStop()
        if preVoiceBtn == Btn && Btn.selected == false {
            
            self.aduioPaly?.stop()
            return
        }
        
        Btn.animaPlay()
        preVoiceBtn = Btn
        
        let key = voiceArrApi[Btn.tag - voiceBtnTag]! as String
        let api = getApi(key)
        
        LDUserInfoNet.sharedInstance.downloadMyResumeVocie(api, success: {
            
            [weak self]  (fileData) in
            self?.aduioPaly = try? AVAudioPlayer.init(data: fileData!)
            self?.aduioPaly?.delegate = self
            self?.aduioPaly?.prepareToPlay()
            
            if self?.aduioPaly?.duration == nil {
                LDShowHUB.shareInstance.showBarStatus("播放失败")
                Btn.animaStop()
                return
            }
            
            
            self?.voiceBtnCurrentTime = (self?.aduioPaly?.currentTime) ?? 0
            
            if self?.aduioPaly?.play() == true {
                self?.addTimer()
            }
            
        }) { (error) in
            
            Btn.animaStop()
            LDShowHUB.shareInstance.showBarStatus("播放失败")
        }
    }
    
    func getApi(key:String) ->String {
        
        let urlStr = LDJobfinderAPI.download.audio.baseAudioUrl + key
        
        return urlStr
    }
    
}
extension LDFinderDetailVoiceCell {
    
    func addTimer() {
        
        currnetTimer = NSTimer.init(timeInterval: 1, target: self, selector: #selector(setVoiceBtnTime), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(currnetTimer!, forMode: NSRunLoopCommonModes)
        currnetTimer!.fire()
    }
    
    func removeTimer() {
        currnetTimer?.invalidate()
        currnetTimer = nil
    }
    
}
extension LDFinderDetailVoiceCell:AVAudioPlayerDelegate {
    //播放停止
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        player.stop()
        preVoiceBtn?.animaStop()
        removeTimer()
    }
}
//布局
extension LDFinderDetailVoiceCell {
    
    func getImgCornerRadious(rad:CGFloat) ->UIImageView {
        
        let imgview = UIImageView.init(image: .setImageWithColor(LDGolbalColor.GreenAssist))
        imgview.layer.cornerRadius = rad
        imgview.layer.masksToBounds = true
        return imgview
    }
    
//    func setTimeLabTitle(btn:baseVoiceButton) {
//        
//        guard voiceArrApi[btn.tag - voiceBtnTag] == nil else {
//            return
//        }
//    }
    
    func getVocieLabPlace() ->UILabel {
        let lab = UILabel.setDetailsLab("没有语音微简历", fontSize: 14, titleColor: LDFontColor.LightGray, Alignment: .Center)
        lab.userInteractionEnabled = true
        
        lab.bk_whenTapped({
            let vc = editMyResumeVC()
            let rootvc = UIApplication.sharedApplication().keyWindow?.rootViewController?.childViewControllers[0] as! LDRootNavVC
            rootvc.pushViewController(vc, animated: true)
        })
        lab.hidden = true
        return lab
    }
    
//    func updataContent() {
//        
//        setTimeLabTitle(myLightBtn!)
//        setTimeLabTitle(myAdvBtn!)
//        setTimeLabTitle(myExpBtn!)
//        setTimeLabTitle(myEduBtn!)
//    }
    
    func setDefaultContent() {
        
        let mar_v:CGFloat = 70
        let dotimg_w:CGFloat = 6
        line_v = UIView()
        line_v?.backgroundColor = LDIconColor.LightGray.colorWithAlphaComponent(0.5)
        
        
        let rootnav = UIApplication.sharedApplication().keyWindow?.rootViewController?.childViewControllers[0] as? LDRTRootNavVC
        
        rootnav?.tapBackNavClosure { [weak self] in
            self?.aduioPaly?.stop()
//            rootnav.popViewControllerAnimated(true)
        }
        
        rootnav?.tapPushNavClosure { [weak self] in
            self?.aduioPaly?.stop()
        }
        
        dotimg1 = getImgCornerRadious(3)
        dotimg2 = getImgCornerRadious(3)
        dotimg3 = getImgCornerRadious(3)
        dotimg4 = getImgCornerRadious(3)
        
        myLightLab = UILabel.setDetailsLab("我的亮点", fontSize: 15, titleColor: LDFontColor.DeepGray, Alignment: .Center)
        myAdvLab = UILabel.setDetailsLab("我的优势", fontSize: 15, titleColor: LDFontColor.DeepGray, Alignment: .Center)
        myExpLab = UILabel.setDetailsLab("工作经历", fontSize: 15, titleColor: LDFontColor.DeepGray, Alignment: .Center)
        myEduLab = UILabel.setDetailsLab("教育经历", fontSize: 15, titleColor: LDFontColor.DeepGray, Alignment: .Center)
        
        myLightBtn = baseVoiceButton()
        myAdvBtn = baseVoiceButton()
        myExpBtn = baseVoiceButton()
        myEduBtn = baseVoiceButton()
        
        myLightBtn?.tag = voiceBtnTag + 0
        myAdvBtn?.tag = voiceBtnTag + 1
        myExpBtn?.tag = voiceBtnTag + 2
        myEduBtn?.tag = voiceBtnTag + 3
        
        
        
        myLightBtn?.bk_whenTapped({ [weak self] in
            self?.tapVoiceBtn((self?.myLightBtn!)!)
            })
        myAdvBtn?.bk_whenTapped({ [weak self] in
            self?.tapVoiceBtn((self?.myAdvBtn!)!)
            })
        myExpBtn?.bk_whenTapped({ [weak self] in
            self?.tapVoiceBtn((self?.myExpBtn!)!)
            })
        myEduBtn?.bk_whenTapped({ [weak self] in
            self?.tapVoiceBtn((self?.myEduBtn!)!)
            })
        
        addSubview(line_v!)
        
        addSubview(dotimg1!)
        addSubview(dotimg2!)
        addSubview(dotimg3!)
        addSubview(dotimg4!)
        
        addSubview(myLightLab!)
        addSubview(myAdvLab!)
        addSubview(myExpLab!)
        addSubview(myEduLab!)
        
        addSubview(myLightBtn!)
        addSubview(myAdvBtn!)
        addSubview(myExpBtn!)
        addSubview(myEduBtn!)
        
        lab1 = getVocieLabPlace()
        lab2 = getVocieLabPlace()
        lab3 = getVocieLabPlace()
        lab4 = getVocieLabPlace()
        addSubview(lab1!)
        addSubview(lab2!)
        addSubview(lab3!)
        addSubview(lab4!)
        
        
        line_v?.snp_makeConstraints(closure: { (make) in
            make.top.equalTo(LDMargin_H*6)
            make.left.equalTo(LDMargin_H*6)
            make.width.equalTo(1)
            make.bottom.equalTo(-LDMargin_H*6)
        })
        
        dotimg1?.snp_makeConstraints(closure: { (make) in
            make.centerX.equalTo(line_v!)
            make.width.height.equalTo(dotimg_w)
            make.top.equalTo(mar_v - LDMargin_V*4)
        })
        dotimg2?.snp_makeConstraints(closure: { (make) in
            make.centerX.equalTo(line_v!)
            make.width.height.equalTo(dotimg_w)
            make.top.equalTo((dotimg1?.snp_bottom)!).offset(mar_v)
        })
        dotimg3?.snp_makeConstraints(closure: { (make) in
            make.centerX.equalTo(line_v!)
            make.width.height.equalTo(dotimg_w)
            make.top.equalTo((dotimg2?.snp_bottom)!).offset(mar_v)
        })
        dotimg4?.snp_makeConstraints(closure: { (make) in
            make.centerX.equalTo(line_v!)
            make.width.height.equalTo(dotimg_w)
            make.top.equalTo((dotimg3?.snp_bottom)!).offset(mar_v)
        })
        
        myLightLab?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((dotimg1?.snp_right)!).offset(LDMargin_H*2)
            make.centerY.equalTo(dotimg1!)
            //            make.width.equalTo(80)
            make.height.equalTo(25)
        })
        myAdvLab?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((dotimg1?.snp_right)!).offset(LDMargin_H*2)
            make.centerY.equalTo(dotimg2!)
            //            make.width.equalTo(80)
            make.height.equalTo(25)
        })
        myExpLab?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((dotimg1?.snp_right)!).offset(LDMargin_H*2)
            make.centerY.equalTo(dotimg3!)
            //            make.width.equalTo(80)
            make.height.equalTo(25)
        })
        myEduLab?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((dotimg1?.snp_right)!).offset(LDMargin_H*2)
            make.centerY.equalTo(dotimg4!)
            //            make.width.equalTo(80)
            make.height.equalTo(25)
        })
        //
        myLightBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myLightLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg1!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        myAdvBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myAdvLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg2!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        myExpBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myExpLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg3!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        myEduBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myEduLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg4!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        
        lab1?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myLightLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg1!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        lab2?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myAdvLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg2!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        lab3?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myExpLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg3!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        lab4?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((myEduLab?.snp_right)!).offset(LDMargin_H*3)
            make.centerY.equalTo(dotimg4!)
            make.width.equalTo(160)
            make.height.equalTo(45)
        })
        
    }
}
